//noDetail：设置不显示详情
//placeholder：设置提示信息

import React from 'react';
// import { AreaData } from '../../utils/data.js'; //地址库
import AreaData from '../../utils/areaData'
import './areaData.scss'
import { Tabs, Select } from 'antd';
import cookie from 'react-cookies';
import debounce from 'lodash/debounce';

import { liteSearchPulishedDeliverAddress } from '../../api/deliveryCenter'

const { TabPane } = Tabs;
const { Option } = Select;

class AreaDataNav extends React.Component {
    constructor(props) {
        super(props);
        this.lastFetchId = 0;
        this.fetchUser = debounce(this.fetchUser, 800);
        this.state = {
            options: [],
            activeKey: '0',
            selAddress: [{
                label: '0',
                value: '',
                title: '请选择'
            }],
            provData: [],
            cityData: [],
            areaData: [],
            prov: '',
            city: '',
            area: '',
            address: '',//详细地址


            provOption: null,
            cityOption: null,
            areaOption: null,
            selectedOptions: [],//选中的列表，含code

            selAddressTextArr: [],
            addressData: [],

            fetching: false,
            isAddressSel: false, //是否选中列表
        }
    }
    componentDidMount() {
        AreaData.data().then(data => {
            // console.log(data)
            this.setState({
                options: data,
                provData: data //省数组
            })
        })
    }

    handleChange = value => {
        // console.log(value, 'Change')
        const { provData, cityData, areaData } = this.state;
        // console.log(cityData)
        this.setState({
            activeKey: value,
            options: value === '0' ? provData : (value === '1' ? cityData : areaData)
        })
    }
    //鼠标移入事件
    handleMouseEnter = e => {
        console.log('222')
        e.preventDefault();
        e.stopPropagation()
    }
    //获得焦点事件
    handleFocus = e => {
        
        const { address, prov, city, area, provOption, cityOption, areaOption, provData } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] : prov;
        const cityNav = this.props.msg ? this.props.msg[1] : city;
        const areaNav = this.props.msg ? this.props.msg[2] : area;
        const addressNav = this.props.msg ? this.props.msg[3] : address;
        // console.log(address, provNav, cityNav, areaNav, provOption,cityOption,areaOption)
        if (areaOption && ((provNav + cityNav + areaNav) !== provOption.value + cityOption.value + areaOption.value)) {
            this.setState({
                prov: '',
                city: '',
                area: '',
                address: '',
                activeKey: '0',
                selAddress: [{
                    label: '0',
                    value: '',
                    title: '请选择'
                }],
                options: provData,
                cityData: [],
                areaData: [],
                provOption: null,
                cityOption: null,
                areaOption: null,
                selectedOptions: [],
                fetching: false
            })
        }
        if (addressNav) {
            // this.fetchUser(addressNav, 'focus');
        } else {
            this.setState({
                fetching: false
            })
        }
    }
    //失去焦点事件
    handleBlur = (e) => {
        // console.log(e)
        const { prov, city, area, provData } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] : prov;
        const cityNav = this.props.msg ? this.props.msg[1] : city;
        const areaNav = this.props.msg ? this.props.msg[2] : area;
        if (!provNav || !cityNav || !areaNav) {
            this.setState({
                prov: '',
                city: '',
                area: '',
                address: '',
                activeKey: '0',
                selAddress: [{
                    label: '0',
                    value: '',
                    title: '请选择'
                }],
                options: provData,
                cityData: [],
                areaData: [],
                provOption: null,
                cityOption: null,
                areaOption: null,
                selectedOptions: [],
                fetching: false
            })
            this.props.getChangeAreaData('', '')
        }
    }
    //
    handleIptChange = value => {
        // console.log(value)

        const { prov, city, area, address, provData, isAddressSel, provOption, cityOption, areaOption } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] : prov;
        const cityNav = this.props.msg ? this.props.msg[1] : city;
        const areaNav = this.props.msg ? this.props.msg[2] : area;
        const addressNav = this.props.msg ? this.props.msg[3] : address;
        const valueText = value[1] ? value[1] : ''
        const selAddressTextArr = [provNav, cityNav, areaNav, !isAddressSel ? addressNav + valueText : addressNav]
        const selectedOptions = [provOption, cityOption, areaOption]
        if (value.length === 0) { //点击清空按钮
            if (address) { //如果存在详细地址，先删除详细地址
                const selAddressTextArr = [provNav, cityNav, areaNav, '']
                const selectedOptions = [provOption, cityOption, areaOption]
                this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
                this.setState({
                    address: '',
                    fetching: true
                })
                // this.fetchUser('');
                return;
            }
            this.props.getChangeAreaData('', '')
            this.input.blur();//清空之后失去焦点，隐藏弹框Q
            this.setState({
                prov: '',
                city: '',
                area: '',
                address: '',
                activeKey: '0',
                selAddress: [{
                    label: '0',
                    value: '',
                    title: '请选择'
                }],
                options: provData,
                cityData: [],
                areaData: [],
                provOption: null,
                cityOption: null,
                areaOption: null,
                selectedOptions: [],
                fetching: false
            })
        } else {
            this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
            this.setState({
                address: !isAddressSel ? address + valueText : address
            })
            if (this.props.noDetail) {
                const selAddressTextArr = [prov, city, area, '']
                const selectedOptions = [provOption, cityOption, areaOption]
                this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
                this.input.blur();//设置禁止输入详情，隐藏弹框Q
                this.setState({
                    address: ''
                })
                return;
            }
        }

    }
    selItem = (item, type) => {
        const value = item.value;
        const code = item.code;
        // console.log(value,code)
        const { selAddress, options, prov, city, provOption, cityOption } = this.state;
        selAddress[type].title = value;
        if (type === '0' && prov && value !== prov) {
            selAddress[1].title = '请选择';
            selAddress.splice(2, 1);
            this.setState({
                prov: value,
                city: '',
                area: '',
                provOption: {
                    value, code
                },
                cityOption: null,
                areaOption: null,
            })
        }
        if (type === '1' && city && value !== city) {
            selAddress[2].title = '请选择';
            this.setState({
                city: value,
                area: '',
                cityOption: {
                    value, code
                },
            })
        }
        const nameAddress = type === '0' ? 'prov' : (type === '1' ? 'city' : 'area')
        const nameAddressOption = type === '0' ? 'provOption' : (type === '1' ? 'cityOption' : 'areaOption')
        if ((type === '0' && selAddress.length === 1) || (type === '1' && selAddress.length === 2)) {
            selAddress.push({
                label: String(parseInt(type) + 1),
                value: '',
                title: '请选择'
            })
        }
        if (type === '2') { //选择区
            this.setState({
                [nameAddress]: value,
                [nameAddressOption]: {
                    value, code
                },
            }, () => {
                const selAddressTextArr = [prov, city, value, '']
                const selectedOptions = [provOption, cityOption, { value, code }]
                this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
                console.log('2323')
                setTimeout(()=>{
                    this.input.blur();//选择区之后失去焦点，隐藏弹框Q
                })
                
            })
        } else {
            const index = options.findIndex(item => item.value === value);
            const data = options[index].children;
            const nameData = type === '0' ? 'cityData' : 'areaData'
            this.setState({
                selAddress,
                activeKey: String(parseInt(type) + 1),
                [nameAddress]: value,
                [nameAddressOption]: {
                    value, code
                },
                options: data, //市数组
                [nameData]: data
            }, () => {
                const selAddressTextArr = [type === '0' ? value : prov, type === '1' ? value : '', '', '']
                const selectedOptions = [type === '0' ? { value, code } : provOption, type === '1' ? { value, code } : '', '']
                this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
            })
        }
    }
    //模糊查询
    fetchUser = (value, type) => {
        // console.log('fetching user', value);
        const { prov, city, area, provOption, cityOption, areaOption } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] : prov;
        const cityNav = this.props.msg ? this.props.msg[1] : city;
        const areaNav = this.props.msg ? this.props.msg[2] : area;
        const addressNav = this.props.msg && this.props.msg[3] ? this.props.msg[3] : '';
        let addressArr = ''
        if (!addressNav || type === 'focus') {
            addressArr = value
        } else {
            addressArr = addressNav + value
        }
        this.setState({
            address: addressArr
        })
        if (this.props.noDetail) {
            const selAddressTextArr = [provNav, cityNav, areaNav, '']
            const selectedOptions = [provOption, cityOption, areaOption]
            this.props.getChangeAreaData(selAddressTextArr, selectedOptions)
            this.input.blur();//设置禁止输入详情，隐藏弹框Q
            this.setState({
                address: ''
            })
            return;
        }
        if (!provNav || !cityNav || !areaNav) {
            return;
        }
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        this.setState({
            data: [],
            fetching: true,
            isAddressSel: false // 未选择操作前变量
        });
        let post_data = {
            'sign_key': '0f680339f284e3712ccfb7240504bf30',
            'u_token': cookie.load('lite_user_info_hz').token,
            'app_type': 27,
            'province': provNav,
            'city': cityNav,
            'area': areaNav,
            'address': addressArr,
        }
        // console.log(addressArr)
        liteSearchPulishedDeliverAddress(post_data).then(res => {
            if (fetchId !== this.lastFetchId) {
                // for fetch callback order
                return;
            }
            const addressData = res.all_addreass ? res.all_addreass.map(el => ({
                value: el,
                text: el
            })) : [];
            const iptStrArr = addressArr.split('')
            addressData.forEach((ele, i) => {
                iptStrArr.forEach(row => {
                    let strAll = ele.value.split('');
                    if (strAll.indexOf(row) !== -1) {
                        var regExp = new RegExp(row, 'g');
                        addressData[i].text = addressData[i].text.replace(regExp, '<span>' + row + '</span>'); //高亮显示输入字符
                    }
                })
            });
            this.setState({ addressData });
        })
    };
    //下拉列表选中, 设置详细地址为选中地址
    setFetch = value => {
        const { prov, city, area, provOption, cityOption, areaOption } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] : prov;
        const cityNav = this.props.msg ? this.props.msg[1] : city;
        const areaNav = this.props.msg ? this.props.msg[2] : area;
        const selAddressTextArr = [provNav, cityNav, areaNav, value];
        const selectedOptions = [provOption, cityOption, areaOption];
        this.props.getChangeAreaData(selAddressTextArr, selectedOptions);
        this.setState({
            address: value,
            isAddressSel: true //是否选中
        })
        this.input.blur();//选中选项之后失去焦点，隐藏弹框Q
    }

    render() {
        const { options, selAddress, activeKey, prov, city, area, address, addressData, fetching } = this.state;
        const provNav = this.props.msg ? this.props.msg[0] || '' : prov;
        const cityNav = this.props.msg ? this.props.msg[1] || '' : city;
        const areaNav = this.props.msg ? this.props.msg[2] || '' : area;
        const addressNav = this.props.msg ? this.props.msg[3] || '' : address;
        // console.log(provNav, cityNav, areaNav, this.props.msg)
        return (
            <Select
                allowClear={true}
                autoClearSearchValue={false}
                className="selectAdress"
                ref={(input) => this.input = input}
                value={(provNav + cityNav + areaNav + addressNav) ? (provNav + cityNav + areaNav + addressNav) : undefined}
                placeholder={this.props.placeholder}
                onClick={this.handleMouseEnter.bind(this)}
                onFocus={this.handleFocus.bind(this)}
                onBlur={this.handleBlur.bind(this)}
                mode="tags"
                onChange={this.handleIptChange.bind(this)}
                showSearch={true}
                // onSearch={this.fetchUser}
                style={{ width: '100%' }}
                dropdownRender={menu => (
                    <div onMouseDown={e => e.preventDefault()}>
                        {!fetching ? <Tabs className="Cascader_options" defaultActiveKey="1" activeKey={activeKey} onChange={this.handleChange.bind(this)}>
                            {selAddress.map(row => (
                                <TabPane tab={row.title} key={row.label} >
                                    {options.map((item, i) => {
                                        return <div className="label" onClick={this.selItem.bind(this, item, row.label)} key={i}>{item.value}</div>
                                    })}
                                    <span className="label"></span>
                                </TabPane>
                            ))}
                        </Tabs> : <div className="fetching_list">
                                {addressData.map((item, i) => (
                                    <div className="li" key={i} onClick={this.setFetch.bind(this, item.value)}> <span dangerouslySetInnerHTML={{ __html: item.text }}></span></div>
                                ))}
                            </div>}
                    </div>
                )}
            >
            </Select>
        )
    }
}
export default AreaDataNav;
